'use client'

import { useEffect, useState } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import api from '@/lib/api'
import Image from 'next/image'
import Link from 'next/link'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Search, SlidersHorizontal } from 'lucide-react'
import debounce from 'lodash/debounce'
import { Suspense } from 'react'
import { useIsMounted } from '@/hooks/useIsMounted'

interface Spot {
  id: number
  name: string
  description: string
  location: string
  price: number
  images: string
  rating: number
  type: string
}

const SPOT_TYPES = [
  { value: 'all', label: '全部类型' },
  { value: '自然景观', label: '自然景观' },
  { value: '人文景观', label: '人文景观' },
]

const SORT_OPTIONS = [
  { value: 'default', label: '默认排序' },
  { value: '-rating', label: '评分从高到低' },
  { value: 'rating', label: '评分从低到高' },
  { value: '-price', label: '价格从高到低' },
  { value: 'price', label: '价格从低到高' },
]

export default function SpotsPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const isMounted = useIsMounted()
  const [spots, setSpots] = useState<Spot[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [type, setType] = useState('all')
  const [sortBy, setSortBy] = useState('default')
  const [isComposing, setIsComposing] = useState(false)

  const fetchSpots = async (params: Record<string, string>) => {
    try {
      setLoading(true)
      const queryString = new URLSearchParams(params).toString()
      const response = await api.get(`/api/spots?${queryString}`)
      setSpots(response.data)
    } catch (error) {
      console.error('Failed to fetch spots:', error)
    } finally {
      setLoading(false)
    }
  }

  // 创建一个防抖的搜索函数
  const debouncedFetchSpots = debounce((params: Record<string, string>) => {
    fetchSpots(params)
  }, 300)

  // 防抖搜索
  const debouncedSearch = debounce((value: string) => {
    const params = new URLSearchParams(searchParams)
    if (value && value.trim()) {
      params.set('search', value)
    } else {
      params.delete('search')
    }
    router.push(`/spots?${params.toString()}`)
    debouncedFetchSpots({ search: value })
  }, 300)

  // 处理搜索输入
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setSearch(value)
    if (!isComposing) {
      debouncedSearch(value)
    }
  }

  // 处理筛选条件变化
  const handleFilterChange = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams)
    if (value && value !== 'all' && value !== 'default') {
      params.set(key, value)
    } else {
      params.delete(key)
    }
    router.push(`/spots?${params.toString()}`)
    fetchSpots({
      ...Object.fromEntries(params.entries())
    })
  }

  const handleCompositionStart = () => {
    setIsComposing(true)
  }

  const handleCompositionEnd = (e: React.CompositionEvent<HTMLInputElement>) => {
    setIsComposing(false)
    const value = e.currentTarget.value
    setSearch(value)
    const params = new URLSearchParams(searchParams)
    if (value && value.trim()) {
      params.set('search', value)
    } else {
      params.delete('search')
    }
    router.push(`/spots?${params.toString()}`)
    fetchSpots({ search: value })
  }

  useEffect(() => {
    if (isMounted) {
      setSearch(searchParams.get('search') || '')
      setType(searchParams.get('type') || 'all')
      setSortBy(searchParams.get('sort_by') || 'default')
      fetchSpots({
        search: searchParams.get('search') || '',
        type: searchParams.get('type') || '',
        sort_by: searchParams.get('sort_by') || ''
      })
    }
  }, [searchParams, isMounted])

  if (!isMounted) {
    return null
  }

  return (
    <div className="bg-white">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex flex-col sm:flex-row gap-4 mb-6">
          {/* 搜索框 */}
          <div className="relative flex-1">
            <Input
              type="text"
              placeholder="搜索景点名称、地区..."
              value={search}
              onChange={handleSearchChange}
              onCompositionStart={handleCompositionStart}
              onCompositionEnd={handleCompositionEnd}
              className="pl-10"
            />
            <Search className="h-4 w-4 absolute left-3 top-3 text-gray-400" />
          </div>

          {/* 筛选器 */}
          <div className="flex gap-4">
            <Select
              value={type}
              onValueChange={(value) => {
                setType(value)
                handleFilterChange('type', value)
              }}
            >
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="景点类型" />
              </SelectTrigger>
              <SelectContent>
                {SPOT_TYPES.map((type) => (
                  <SelectItem key={type.value} value={type.value}>
                    {type.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select
              value={sortBy}
              onValueChange={(value) => {
                setSortBy(value)
                handleFilterChange('sort_by', value)
              }}
            >
              <SelectTrigger className="w-[140px]">
                <SelectValue placeholder="排序方式" />
              </SelectTrigger>
              <SelectContent>
                {SORT_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* 景点列表 */}
        {loading ? (
          <div>加载中...</div>
        ) : (
          <div className="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:gap-x-8">
            {spots.map((spot) => (
              <Link key={spot.id} href={`/spots/${spot.id}`} className="group">
                <div className="aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-lg bg-gray-200">
                  <Image
                    src={spot.images.split(',')[0]}
                    alt={spot.name}
                    width={500}
                    height={300}
                    className="h-full w-full object-cover object-center group-hover:opacity-75"
                  />
                </div>
                <h3 className="mt-4 text-sm text-gray-700">{spot.name}</h3>
                <p className="mt-1 text-lg font-medium text-gray-900">¥{spot.price}</p>
                <div className="mt-1 flex items-center">
                  {[...Array(5)].map((_, i) => (
                    <svg
                      key={i}
                      className={`h-5 w-5 ${
                        i < spot.rating ? 'text-yellow-400' : 'text-gray-200'
                      }`}
                      fill="currentColor"
                      viewBox="0 0 20 20"
                    >
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  ))}
                </div>
              </Link>
            ))}
          </div>
        )}

        {!loading && spots.length === 0 && (
          <div className="text-center text-gray-500 py-8">
            没有找到符合条件的景点
          </div>
        )}
      </div>
    </div>
  )
} 